<!DOCTYPE html>
<html class="x-admin-sm">

<head>
    <meta charset="UTF-8">
    <title>宿舍管理系统</title>
    <meta name="renderer" content="webkit">
    <meta name="csrf-token" content="{{ csrf_token() }}" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
        content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />

    <link rel="stylesheet" href="{{ asset('css/font.css') }}">
    <link rel="stylesheet" href="{{ asset('css/xadmin.css') }}">
    <script type="text/javascript" src="{{ asset('lib/layui/layui.js') }}" charset="utf-8"></script>
    <script type="text/javascript" src="{{ asset('js/xadmin.js') }}"></script>

    <!-- 让IE8/9支持媒体查询，从而兼容栅格 -->
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>
        #subitem+div {
            width: 500px !important;
        }

        .category-section {
            margin-bottom: 20px;
            border: 1px solid #eee;
            border-radius: 4px;
            padding: 15px;
        }

        .category-title {
            font-size: 16px;
            font-weight: bold;
            color: #333;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
            margin-bottom: 15px;
        }

        .rating-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #f5f5f5;
        }

        .item-name {
            font-size: 14px;
            color: #333;
            max-width: 60%;
        }

        .score-input {
            display: flex;
            align-items: center;
        }

        .max-score {
            margin-left: 10px;
            font-size: 12px;
            color: #999;
        }

        .remark-section {
            margin-top: 20px;
        }

        .remark-title {
            font-size: 14px;
            font-weight: bold;
            color: #333;
            margin-bottom: 10px;
        }

        .total-score {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            padding: 15px;
            font-size: 16px;
            margin-top: 20px;
            border-top: 1px solid #eee;
        }

        .total-label {
            color: #333;
            margin-right: 10px;
        }

        .total-value {
            color: #FF5722;
            font-weight: bold;
        }
    </style>
</head>

<body>
    <div class="layui-fluid">
        <div class="layui-row">
            <form class="layui-form rating-form" id="ratingForm">
                @csrf
                <!-- 评分周期选择 -->
                <div class="layui-form-item">
                    <label class="layui-form-label"><span class="x-red">*</span>评分周期</label>
                    <div class="layui-input-inline">
                        <select name="period_id" lay-verify="required">
                            <option value="">请选择评分周期</option>
                            @foreach ($periods as $id => $name)
                                <option value="{{ $id }}" @if (isset($rating) && $rating->period_id == $id) selected @endif>
                                    {{ $name }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                </div>

                <!-- 宿舍选择 -->
                <div class="layui-form-item">
                    <label class="layui-form-label"><span class="x-red">*</span>宿舍楼</label>
                    <div class="layui-input-inline">
                        <select name="building_id" lay-verify="required" lay-filter="building" id="building">
                            <option value="">请选择宿舍楼</option>
                            @foreach ($buildings as $id => $name)
                                <option value="{{ $id }}" @if (isset($rating) && $rating->dorm->building_id == $id) selected @endif>
                                    {{ $name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <label class="layui-form-label"><span class="x-red">*</span>宿舍</label>
                    <div class="layui-input-inline">
                        <select id="dorm" name="dorm_id" lay-verify="required">
                            @if (isset($rating))
                                <option value="{{ $rating->dorm_id }}">{{ $rating->dorm->code }}</option>
                            @else
                                <option value="">请选择宿舍</option>
                            @endif
                        </select>
                    </div>
                </div>


                <!-- 评分分类 -->
                @foreach ($ratingCategories as $category)
                    <div class="category-section">
                        <div class="category-title">{{ $category->category_name }} ({{ $category->total_score }}分)
                        </div>

                        @foreach ($category->ratingSubitems as $item)
                            <div class="rating-item">
                                <div class="item-name">{{ $item->subitem_name }}</div>
                                <div class="score-input">
                                    <input type="number" name="scores[{{ $item->id }}]"
                                        value="{{ isset($rating) ? $scores[$item->id] ?? 0 : 0 }}" min="0"
                                        max="{{ $item->subitem_score }}" class="layui-input score-input-field"
                                        style="width: 60px; text-align: center;" onchange="calculateTotal()">
                                    <div class="max-score">/{{ $item->subitem_score }}</div>
                                </div>
                            </div>
                        @endforeach
                    </div>
                @endforeach

                <!-- 备注信息 -->
                <div class="remark-section">
                    <div class="remark-title">备注信息:</div>
                    <textarea name="remark" placeholder="请输入备注信息..." class="layui-textarea" maxlength="500">{{ $rating->remark ?? '' }}</textarea>
                </div>

                <!-- 总分统计 -->
                <div class="total-score">
                    <div class="total-label">总分:</div>
                    <div class="total-value"><span
                            id="totalScore">{{ isset($rating) ? $rating->get_score : 0 }}</span>分</div>
                    <input type="hidden" name="get_score" id="totalScoreInput"
                        value="{{ isset($rating) ? $rating->get_score : 0 }}">
                </div>

                <!-- 提交按钮 -->
                <div class="layui-form-item" style="margin-top: 20px;">
                    <button type="button" class="layui-btn layui-btn-normal" lay-submit
                        lay-filter="formSubmit">提交评分</button>
                </div>
            </form>
        </div>
    </div>
    <script>
        layui.use(['form', 'layer', 'jquery'], function() {
            var form = layui.form;
            var layer = layui.layer;
            var $ = layui.jquery;
            var totalScore = {{ $totalScore ?? 0 }};

            // 计算总分
            window.calculateTotal = function() {
                totalScore = 0;
                $('.score-input-field').each(function() {
                    var score = parseInt($(this).val()) || 0;
                    totalScore += score;
                });
                $('#totalScore').text(totalScore);
                $('#totalScoreInput').val(totalScore);
            };
            // 替换静态数据部分
            form.on('select(building)', function(data) {
                var building_id = data.value;
                var dormSelect = $('#dorm');

                dormSelect.empty();

                if (building_id === '') {
                    dormSelect.append('<option value="">请先选择宿舍楼</option>');
                } else {
                    // 发起AJAX请求获取宿舍数据
                    $.ajax({
                        url: '/api/getDormsByBuilding',
                        type: 'GET',
                        data: {
                            building_id: building_id
                        },
                        success: function(res) {
                            dormSelect.append('<option value="">请选择宿舍</option>');
                            $.each(res, function(index, dorm) {
                                dormSelect.append('<option value="' + dorm.id + '">' +
                                    dorm.code + '</option>');
                            });
                            form.render('select');
                        }
                    });
                }
            });

            // 表单提交
            form.on('submit(formSubmit)', function(data) {
                if (totalScore === 0) {
                    layer.msg('请至少填写一项评分', {
                        icon: 2
                    });
                    return false;
                }
                // 转换表单数据格式
                var formData = {
                    _token: data.field._token,
                    period_id: data.field.period_id,
                    building_id: data.field.building_id,
                    dorm_id: data.field.dorm_id,
                    remark: data.field.remark || '',
                    dormRatings: [],
                    get_score: data.field.get_score,
                };

                // 处理评分项
                for (var key in data.field) {
                    if (key.startsWith('scores[')) {
                        var subitemId = key.match(/\[(\d+)\]/)[1];
                        formData.dormRatings.push({
                            period_id: formData.period_id,
                            dorm_id: formData.dorm_id,
                            subitem_id: subitemId,
                            score: data.field[key],
                            rating_date: new Date().toLocaleDateString(),
                        });
                    }
                }
                var loading = layer.load(2);
                $.ajax({
                    url: "{{ route('dorm-rating-mains.store') }}",
                    type: "POST",
                    data: JSON.stringify(formData),
                    contentType: "application/json", // 设置内容类型
                    headers: {
                        "Accept": "application/json", // 设置Accept头部
                        "X-CSRF-TOKEN": data.field._token // 确保CSRF token被传递
                    },
                    success: function(res) {
                        layer.close(loading);
                        if (res.message == 'DormRatingRemark created.') {
                            layer.msg("提交成功", {
                                icon: 1
                            }, function() {
                                //关闭当前frame
                                xadmin.close();
                                // 可以对父窗口数据表进行刷新
                                parent.layui.table.reload('data-table');
                            });
                        } else {
                            layer.msg(res.message || '提交失败', {
                                icon: 2
                            });
                        }
                    },
                    error: function(xhr) {
                        layer.close(loading);
                        var errors = xhr.responseJSON.errors;
                        if (errors) {
                            var errorMsg = '';
                            for (var key in errors) {
                                errorMsg += errors[key][0] + '<br>';
                            }
                            layer.msg(errorMsg, {
                                icon: 2
                            });
                        } else {
                            layer.msg('网络错误，请稍后重试', {
                                icon: 2
                            });
                        }
                    }
                });
                return false;
            });
        });
    </script>
</body>

</html>
